package com.blog.service.service;

import com.blog.check.check.CheckResult;
import com.blog.check.check.ProfileCheck;
import com.blog.check.result.Result;
import com.blog.check.resultenum.ProfileChkRsEnum;
import com.blog.dao.domain.ProfileDO;
import com.blog.dao.domain.UserDO;
import com.blog.exception.ServiceException;
import com.blog.form.ProfileForm;
import com.blog.service.constant.SysPropertiesKeyConsts;
import com.blog.service.dto.ProfileDTO;
import com.blog.until.BeanCopierUtil;
import com.blog.until.RandomUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;


import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;

/**
 * 配置文件服务
 *
 * @author 泡面ing
 * @date 2021/11/17
 */
@Service
public class ProfileService extends BaseService {

    private ProfileCheck profileCheck;

    @Autowired
    public void setProfileCheck(ProfileCheck profileCheck){
        this.profileCheck = profileCheck;
    }

    @Transactional(rollbackFor=Exception.class)
    public Result get() throws Exception{

        try {

            String username = getUsername();
            UserDO userDO = userDAO.get(username);

            ProfileDTO profileDTO = new ProfileDTO();
            ProfileDO profileDO = profileDAO.get(userDO.getProfileId());
            if (profileDO != null){
                profileDTO = getShowDTO(profileDO);
            }
            return Result.success(profileDTO);
        }catch (Exception e){
            throw new ServiceException(e);
        }
    }

    /**
     * DO向dto赋值
     */

    private ProfileDTO getShowDTO(ProfileDO profileDO) throws IOException {
        ProfileDTO profileDTO = new ProfileDTO();
        profileDTO.setId(profileDO.getId());
        profileDTO.setAddress(profileDO.getAddress());
        profileDTO.setNickName(profileDO.getNickName());
        profileDTO.setSign(profileDO.getSign());

        File file = new File(profileDO.getImageName());
        if (file.exists()){
            byte[] bytes = FileUtils.readFileToByteArray(file);
            String icon = getImageBase64Prefix(file) + "," +Base64Utils.encodeToString(bytes);
            profileDTO.setImageName(icon);
        }
        return profileDTO;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result save(ProfileForm profileForm){
        try {
//            获取环境变量
            Properties properties = getProperties(SYS_PROPERTIES_FILEPATH);
//            搜索指定的键，获取文件中的文件路径
            String iconPath = properties.getProperty(SysPropertiesKeyConsts.ICON_PATH);
//            文件路径判断非空
            if (StringUtils.isBlank(iconPath)){
                logger.error(SysPropertiesKeyConsts.ICON_PATH + " is blank。");
                throw new Exception(SysPropertiesKeyConsts.ICON_PATH + " is blank。");
            }
            String base64Prefix = StringUtils.substringBefore(profileForm.getImageName(), ",");
            String suffix = getImageSuffix(base64Prefix);
            Date date = systemDAO.getCurrentSqlDateTime();

            String destPath = iconPath + "/" + RandomUtil.getRandomCharAndNum(6) + "_"
                    + DateFormatUtils.format(date, "yyyyMMddHHmmss") + suffix;

            ProfileDO profileDO = buildSaveProfile(profileForm,destPath);
            profileDAO.save(profileDO);


            String icon = StringUtils.substringAfter(profileForm.getImageName(), ",");
            byte[] bytes = Base64Utils.decodeFromString(icon);

            FileUtils.writeByteArrayToFile(new File(destPath), bytes);

            return Result.success();
        }catch (Exception e){
            throw new ServiceException(e);
        }
    }

    private ProfileDO buildSaveProfile(ProfileForm profileForm,String destPath)
            throws InstantiationException, IllegalAccessException {
        ProfileDO profileDO = BeanCopierUtil.create(profileForm,ProfileDO.class);
        profileDO.setId(profileForm.getId());
        profileDO.setAddress(profileForm.getAddress());
        profileDO.setNickName(profileForm.getNickName());
        profileDO.setSign(profileForm.getSign());
        profileDO.setImageName(destPath);
        return profileDO;
    }
    @Transactional(rollbackFor = Exception.class)
    public Result update(ProfileForm profileForm){
        try{
            String username = getUsername();
            UserDO userDO = userDAO.get(username);

            CheckResult checkResult = profileCheck.checkUpdate(userDO.getProfileId());
            if (checkResult.getCode() != ProfileChkRsEnum.SUCCESS.getCode()){
                logger.error(logInfo(checkResult));
                return Result.failure(checkResult);
            }

            ProfileDO profileDO = profileDAO.get( userDO.getProfileId());
            String oldIconPath = profileDO.getImageName();

            String icon = "";
            File file = new File(profileDO.getImageName());
            String destPath = null;
            if (file.exists()){
                byte[] bytes = FileUtils.readFileToByteArray(file);
                icon = Base64Utils.encodeToString(bytes);
            }
            String common = ",";
            if (!StringUtils.substringAfter(profileForm.getImageName(),common).equals(icon)){
                destPath = makeDestPath(profileForm.getImageName());
            }


            profileDO = buildUpdateProfile(userDO.getProfileId(),profileForm,destPath);
            profileDAO.update(profileDO);

            if (!oldIconPath.equals(profileDO.getImageName())) {
                icon = StringUtils.substringAfter(profileForm.getImageName(), ",");
                byte[] bytes = Base64Utils.decodeFromString(icon);

                FileUtils.writeByteArrayToFile(new File(profileDO.getImageName()), bytes);

                file = new File(oldIconPath);
                boolean result;
                if (file.exists()) {
                    result = file.delete();
                    System.out.println(result);
                }
            }
            return Result.success();

        }catch(Exception e){
            throw new ServiceException(e);
        }

    }

    private ProfileDO buildUpdateProfile(String id, ProfileForm profileForm, String destPath)
            throws InstantiationException, IllegalAccessException{
        ProfileDO profileDO = profileDAO.get(id);
        ProfileDO newProfileDO = BeanCopierUtil.create(profileDO,ProfileDO.class);
        if (profileForm.getAddress() != null){
            newProfileDO.setAddress(profileForm.getAddress());
        }
        if(profileForm.getNickName() != null){
            newProfileDO.setNickName(profileForm.getNickName());
        }
        if(profileForm.getSign() != null){
            newProfileDO.setSign(profileForm.getSign());
        }
        if(profileForm.getImageName() != null){
            newProfileDO.setImageName(destPath);
        }
        return newProfileDO;
    }

}
